package com.wuliu.driver.service;

import com.wuliu.driver.mapper.FreightsourcesMapper;
import com.wuliu.driver.mapper.OrdersMapper;
import com.wuliu.driver.pojo.Freightsources;
import com.wuliu.driver.pojo.Orders;
import com.wuliu.driver.util.Code;
import com.wuliu.driver.util.Erweima;
import com.wuliu.driver.util.MapUtil;
import com.wuliu.driver.util.Result;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrdersServiceImpl implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private FreightsourcesMapper freightsourcesMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MapUtil mapUtil;
    @Autowired
    private Erweima erweima;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Result select(Integer did) {
        Orders select = ordersMapper.select(did);
        if (select != null){
            return new Result(Code.GET_OK,select,"查询成功");
        }
        return new Result(Code.GET_ERR,"查询失败");
    }

    //设置事务的回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result add(Map map) {
        RLock lock = redissonClient.getLock("lock");
        try {
            lock.tryLock(3,10, TimeUnit.MILLISECONDS);//上锁
            System.out.println("加锁成功,开始执行业务");
            String string = map.get("sourceid").toString();
            //获取当前时间
            LocalDateTime  date = LocalDateTime.now();
            System.out.println(string);
            //获取商品信息
            int sourceid = Integer.parseInt(string);
            Freightsources freightsources = freightsourcesMapper.selectOrders(sourceid);
            System.out.println("fffff"+freightsources);
            //获取车辆数量
            Integer cid = Integer.parseInt(map.get("cid").toString());
            //获取用户id
            Integer did = Integer.parseInt(map.get("did").toString());
            Orders orders = new Orders();
            orders.setCid(cid);
            orders.setDid(did);
            orders.setSid(sourceid);
            orders.setInstime(date);
            if (freightsources.getTotalweights()>35.0){
                orders.setSum(35.0);
                freightsources.setTotalweights(freightsources.getTotalweights()-35);
            }else {
                orders.setSum(freightsources.getTotalweights());
                freightsources.setTotalweights(0.0);
            }
            orders.setHandmoney(orders.getSum()*Double.parseDouble(freightsources.getUnitprice().toString()));
            orders.setStatus(0);
            String s = UUID.randomUUID().toString().substring(11) + did;
            String qrCode = erweima.createQRCode(s,s);
            System.out.println("二维码地址"+qrCode);
            System.out.println("随机生成的数据"+s);
            orders.setExt3(s);
            orders.setQrcode(qrCode);
            //向订单表中添加数据
            int add = ordersMapper.add(orders);
            if (add>0){
                //修改商品表中的库存
                int update = freightsourcesMapper.updateOrder(freightsources);
                //s为生成的随机数，将订单id存到redis中，设置过期时间2小时
                redisTemplate.opsForValue().set(s, orders.getId().toString(), 2, TimeUnit.HOURS);
                //生成一个12位的随机数，做为提货单
                return new Result(Code.IMPORT_OK,"抢单成功");
            }else {
                return new Result(Code.IMPORT_ERR,"抢单失败");
            }
        }
        catch (Exception e){
            e.printStackTrace();
            return new Result(Code.IMPORT_ERR,"网络有点差");
        }
        finally {
            lock.unlock();
        }
    }

    //取消运单
    @Override
    public Result upd(Integer id,Integer status) {
        int upd = ordersMapper.upd(id, status);
        if (upd>0){
            return new Result(Code.UPDATE_OK,"修改成功");
        }
        return new Result(Code.UPDATE_ERR,"修改失败");
    }

    @Override
    public Result ka(Map map) {
        System.out.println(map);
        Map sid = freightsourcesMapper.select(Integer.parseInt(map.get("sid").toString()));
        System.out.println(sid);
        String stationLocation = sid.get("station_location").toString();
        String[] split = stationLocation.split(",");
        double latitude = Double.parseDouble(split[1]);
        double longitude = Double.parseDouble(split[0]);
        double h_latitude = Double.parseDouble(map.get("latitude").toString());
        double h_longitude = Double.parseDouble(map.get("longitude").toString());
        double distance = mapUtil.getDistance(h_latitude, h_longitude, latitude, longitude);
        System.out.println(distance);
        if (distance<10){
            //修改订单状态
            int upd = ordersMapper.upd(Integer.parseInt(map.get("id").toString()), 2);
            if (upd>0){
                return new Result(Code.UPDATE_OK,"打卡成功");
            }
            return new Result(Code.UPDATE_ERR,"打卡失败");
        }
        return new Result(Code.UPDATE_ERR,"请在站点500米内打卡");
    }

    //提交空车，装车重量图片
    @Override
    public Result upload(Orders orders) {
        LocalDateTime date = LocalDateTime.now();
        orders.setUpdtime(date);
        orders.setStatus(3);
        int updimg = ordersMapper.updimg(orders);
        if (updimg>0){
            return new Result(Code.UPDATE_OK,"上传成功");
        }
        return new Result(Code.UPDATE_ERR,"上传失败");
    }

    //卸车
    @Override
    public Result upd(Orders orders) {
        System.out.println(orders);
        //首先查询表中的数据
        Orders select = ordersMapper.selectOrder(orders.getId());
        LocalDateTime date = LocalDateTime.now();
        orders.setUnloadtime(date);
        System.out.println(orders);
        System.out.println(select);
        orders.setLoss(select.getActualsum()-orders.getUnloadsum()+"");
        int unload = ordersMapper.unload(orders);
        if (unload>0){
            return new Result(Code.UPDATE_OK,"卸车成功");
        }else {
            return new Result(Code.UPDATE_ERR,"卸车失败");
        }
    }

    @Override
    public Result selectOrder(Integer id) {
        Map map = ordersMapper.selectOrders(id);
        if (map!=null){
            return new Result(Code.GET_OK,map,"查询成功");
        }
        return new Result(Code.GET_ERR,"查询失败");
    }

    @Override
    public Result finish(Integer id) {
        int upd = ordersMapper.upd(id, 4);
        if (upd>0){
            //表示订单完成
            //开始向队列中发送消息
            rabbitTemplate.convertAndSend("orders_finish",id);
            return new Result(Code.UPDATE_OK,"提交成功");
        }else {
            return new Result(Code.UPDATE_ERR,"提交失败");
        }
    }

    //查询该用户的所有订单
    @Override
    public Result selectAll(Orders orders) {
        List<Map> maps = ordersMapper.selectAll(orders);
        System.out.println(maps);
        if (maps!=null){
            return new Result(Code.GET_OK,maps,"查询成功");
        }
        return new Result(Code.GET_ERR,"查询失败");
    }

}
